/*
 * @(#)DonateServiceImpl.java 2019年12月20日 下午2:13:36
 * Copyright 2019 zmr, Inc. All rights reserved. 
 * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.wind.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.wind.domain.Diary;
import com.wind.mapper.DiaryMapper;
import com.wind.service.IDiaryService;

import cn.hutool.core.util.RandomUtil;

/**
 * <p>File：DonateServiceImpl.java</p>
 * <p>Title: </p>
 * <p>Description:</p>
 * <p>Copyright: Copyright (c) 2019 2019年12月20日 下午2:13:36</p>
 * <p>Company: zmrit.com </p>
 * @author zmr
 * @version 1.0
 */
@Service
public class DiaryServiceImpl implements IDiaryService
{
    private static final String           KEY_ALL_DIARY_LIST = "all_diary_list_";

    @Autowired
    private DiaryMapper                   diaryMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Resource(name = "redisTemplate")
    private ListOperations<String, Diary> opsList;

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.IDiaryService#insert(com.ruoyi.system.domain.Diary)
     */
    @Override
    public int insert(Diary diary)
    {
        return diaryMapper.insertSelective(diary);
    }

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.IDiaryService#selectDiaryById(java.lang.Integer)
     */
    @Override
    public Diary selectDiaryById(int id)
    {
        return diaryMapper.selectByPrimaryKey(id);
    }

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.IDiaryService#selectDiaryRandom()
     */
    @Override
    public Diary selectDiaryRandom(int cate)
    {
        String key = KEY_ALL_DIARY_LIST + cate;
        if (!redisTemplate.hasKey(key))
        {
            List<Diary> list = selectDiaryList(new Diary().setStatus(1).setCate(cate));
            if (null != list && list.size() > 0)
            {
                opsList.leftPushAll(key, list);
                redisTemplate.expire(key, 5, TimeUnit.MINUTES);
            }
        }
        Long size = opsList.size(key);
        if (null != size && size > 0)
        {
            long index = RandomUtil.randomLong(size);
            return opsList.index(key, index);
        }
        return null;
    }

    /* (non-Javadoc)
     * @see com.ruoyi.system.service.IDiaryService#selectDiaryList(com.ruoyi.system.domain.Diary)
     */
    @Override
    public List<Diary> selectDiaryList(Diary diary)
    {
        return diaryMapper.select(diary);
    }
}
